package offer;

import java.util.HashMap;
import java.util.Map;

public class EX7 {

      public class TreeNode {
          int val;
          TreeNode left;
          TreeNode right;
          TreeNode(int x) { val = x; }
      }

      Map<Integer,Integer> map;
      int p = 0;

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder.length<=0||inorder.length<=0){
            return null;
        }
        map= new HashMap<Integer,Integer>();
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i],i);
        }
        return help(preorder,inorder,0,preorder.length-1);
    }
    public TreeNode help(int[] preorder,int[] inorder,int l,int r){
        if(l>r){
            return null;
        }
        int v =preorder[p++];
        int mid = map.get(v);
        TreeNode treeNode = new TreeNode(inorder[mid]);
        treeNode.left = help(preorder,inorder,l,mid-1);
        treeNode.right = help(preorder,inorder,mid+1,r);
        return treeNode;
    }
}
